import React, { Component } from 'react';
import { connect } from 'dva';
import styles from './distributionUser.css';
import sty from './index.css';
// import { Dispatch, AnyAction } from 'redux';
import {
  Button,
  Table,
  Tabs,
  Select,
  Input,
  Pagination,
  Modal,
  Tree,
  message,
  Spin,
  Icon,
} from 'antd';
import { DeviceListsItem } from '@/models/connect';
import { RouteComponentProps } from 'react-router-dom';
import { Dispatch, AnyAction } from 'redux';
import {
  allocatedList,
  unallocatedList,
  insertUserRole,
  deleteRoleUser,
} from '@/services/systemDevice';
import produce, { Draft } from 'immer';
import { router } from 'umi';
import { isMenuVisible } from '@/utils/utils';

const { TreeNode } = Tree;
const { Option } = Select;
const { Column } = Table;
const { TabPane } = Tabs;
interface DeviceListsProps extends RouteComponentProps<{ roleId: string }> {
  loading: boolean;
  dispatch: Dispatch<AnyAction>;
}
class distributionUser extends Component<DeviceListsProps> {
  constructor(props: DeviceListsProps) {
    super(props);
    const aaa = this.props.match.params.roleId;
    this.state = {
      // roleId: aaa,
      isShowModel: false, // 打开弹窗
      expandedKeys: [], //树形展开的节点key
      autoExpandParent: true, //自动展开父级
      checkedKeys: [], // 选中的节点id
      selectedKeys: [], // 点击的节点id
      curRoleId: undefined, // 点击表格某一行的角色Id
      curRoleName: '', // 点击表格某一行的角色名称
      selcTree: [], // 树形数据
      pageTotal: 11, // 列表总数
      pageTotal1: 11, //未绑定角色用户列表总数
      pageSize1: 5,
      pageNum1: 1, //未绑定角色用户页面
      tableData: [], // 表格数据
      tableData1: [],
      roleId: '', // 搜索框的角色id
      roleName: '', // 搜索框的角色名称
      pageNum: 1, // 当前页
      pageSize: 10, // 每页展示数据的条数
      roleDevicePowerList: [], // 选中节点的数据
      isPatching: false, // 是否正在加载中
      parameters: {
        roleId: aaa, //角色id
        surLoginName: '', //用户名称
        surPhoneNumber: '', //手机号码
        pageNum: 1, //页码
        pageSize: 10, //每页显示条数
      },
      parameters1: {
        //未绑定角色用户查询条件
        roleId: aaa, //角色id
        surLoginName: '', //用户名称
        surPhoneNumber: '', //手机号码
        pageNum: 1, //页码
        pageSize: 5, //每页显示条数
      },
      remove: {
        surRoleId: '',
        surUserIds: '',
      },
    };
  }
  handleLoading = async () => {
    let [err, data] = await allocatedList(this.state.parameters);
    if (!err) {
      this.setState(
        {
          tableData: data.rows,
          pageTotal: data.total,
        },
        () => {},
      );
    }
  };
  handleUnaAllocatedRoleUser = async () => {
    let [err, data] = await unallocatedList(this.state.parameters1);
    if (!err) {
      this.setState(
        {
          tableData1: data.rows,
          pageTotal1: data.total,
        },
        () => {},
      );
    }
  };
  handledelete = async () => {
    console.log(this.state.tableData);
    if(this.state.tableData.length === 1) {
      this.setState(
        produce((draft: Draft): void => {
          draft.parameters.pageNum = draft.parameters.pageNum - 1;
          draft.pageNum = draft.parameters.pageNum;
        })
      );
    }
    let res = await deleteRoleUser(this.state.remove);
    message.info(res[2]);
    this.setState(
      produce((draft: Draft): void => {
        draft.remove.surRoleId = '';
        draft.remove.surUserIds = '';
        draft.delectShowModel = false;
      }),
      () => {
        this.handleLoading();
      },
    );
  };
  deleteRoleUser = async (_record: any) => {
    this.setState(
      produce((draft: Draft): void => {
        draft.remove.surRoleId = this.state.parameters1.roleId;
        draft.remove.surUserIds = _record.surUserId;
        draft.delectShowModel = true;
      }),
    );
  };
  insertUserRole = async (_record: any) => {
    let roleId = this.state.parameters1.roleId;
    let userIds = _record.surUserId;
    let parame = { roleId, userIds };
    let res = await insertUserRole(parame);
    message.info(res[2]);
    this.setState(
      produce((draft: Draft): void => {
        draft.parameters1.pageNum = 1;
        draft.pageNum1 = 1;
      }),
      () => {
        this.handleUnaAllocatedRoleUser();
      },
    );
  };
  componentWillMount() {
    this.handleLoading();
  }

  render() {
    return (
      <div className={styles.container}>
        <div className={styles.containerTitle}>位置: 角色管理/分配用户</div>
        <div className={sty.btnAction}>
          {isMenuVisible('system:roleUser:insertUserRole') && (
            <Button
              type="link"
              onClick={() => {
                this.setState(
                  {
                    isShowModel: true,
                  },
                  () => {
                    this.handleUnaAllocatedRoleUser();
                  },
                );
              }}
            >
              <Icon type="plus" />
              新增
            </Button>
          )}
          <Button type="link" onClick={() => router.push('/system')}>
            <Icon type="rollback" />
          </Button>
        </div>
        <div style={{ clear: 'both' }}>
          <div className={styles['dev-search']}>
            <div className={styles['dev-search-select']}>
              <Input
                addonBefore="登录名称"
                type="text"
                value={this.state.parameters.surLoginName}
                onChange={e => {
                  let val = e.target.value;
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.parameters.surLoginName = val;
                      draft.roleId = val;
                    }),
                    () => {},
                  );
                }}
              />
            </div>
            <div className={styles['dev-search-select']}>
              <Input
                addonBefore="电话号码"
                type="text"
                value={this.state.parameters.surPhoneNumber}
                onChange={e => {
                  const reg = /^-?(0|[1-9][0-9]*)(\.[0-9]*)?$/;
                  let datachange = e.target.value.replace(/[, ]/g, '');
                  if (
                    (!isNaN(datachange) && reg.test(datachange)) ||
                    datachange === '' ||
                    datachange === '-'
                  ) {
                    this.setState(
                      produce((draft: Draft): void => {
                        draft.parameters.surPhoneNumber = datachange;
                        // draft.value = datachange;
                      }),
                    );
                  } else {
                    this.setState(
                      produce((draft: Draft): void => {
                        draft.parameters.surPhoneNumber = '';
                        // draft.value = '';
                      }),
                      () => {
                        message.error('请填写数字');
                      },
                    );
                  }
                }}
              />
            </div>

            <Button
              className={styles.search}
              size="large"
              onClick={() => {
                this.setState(
                  produce((draft: Draft): void => {
                    draft.parameters.pageNum = 1;
                    draft.pageNum = 1;
                  }),
                  () => {
                    this.handleLoading();
                  },
                );
              }}
            >
              搜索
            </Button>
            <Button
              className={styles.search}
              size="large"
              onClick={() => {
                this.setState(
                  produce((draft: Draft): void => {
                    draft.parameters.surPhoneNumber = '';
                    draft.parameters.surLoginName = '';
                  }),
                  () => {},
                );
              }}
            >
              重置
            </Button>
          </div>
        </div>

        <div className={'tableArea'}>
          <Table dataSource={this.state.tableData} pagination={false} rowKey="surUserId">
            <Column title="登陆名称" align="center" dataIndex="surLoginName" key="surLoginName" />
            <Column title="用户名称" align="center" dataIndex="surUserName" key="surUserName" />
            <Column title="邮箱" align="center" dataIndex="surEmail" key="surEmail" />
            <Column
              title="手机号码"
              align="center"
              dataIndex="surPhoneNumber"
              key="surPhoneNumber"
            />
            <Column
              title="用户状态"
              align="center"
              dataIndex="surStatus"
              key="surStatus"
              render={(_text: number, _record: any) => {
                return _record.surStatus == 0 ? (
                  <span style={{ color: 'rgb(69, 235, 167)' }}>正常</span>
                ) : (
                  <span style={{ color: '#cb3203' }}>停用</span>
                );
              }}
            />
            <Column title="创建时间" align="center" dataIndex="surCreateTime" key="surCreateTime" />
            <Column
              title="操作"
              align="center"
              key="action"
              render={(_text: number, _record: any) => (
                <span>
                  {isMenuVisible('system:role:deleteUserRole') && (
                    <a
                      onClick={() => {
                        this.deleteRoleUser(_record);
                      }}
                      style={{ color: '#cb3203' }}
                    >
                      取消授权
                    </a>
                  )}
                </span>
              )}
            />
          </Table>
        </div>
        <div className={sty.pageArea}>
          <Pagination
            className={styles.pageHandle}
            showQuickJumper={false}
            defaultCurrent={this.state.pageNum}
            pageSize={10}
            total={this.state.pageTotal}
            current={this.state.pageNum}
            onChange={pageNo => {
              let datachange = pageNo;
              this.setState(
                produce((draft: Draft): void => {
                  draft.parameters.pageNum = datachange;
                  draft.pageNum = datachange;
                }),
                () => {
                  this.handleLoading();
                },
              );
            }}
          />
          <span className="pagination-title-box">
            第{this.state.parameters.pageNum}/
            {Math.ceil((this.state.pageTotal ? this.state.pageTotal : 0) / this.state.pageSize)}页
            共{this.state.pageTotal}条
          </span>
        </div>
        <Modal
          title="系统提示"
          visible={this.state.delectShowModel}
          className="delete_role_box"
          onCancel={() => {
            // this.setState({ delectShowModel: false ,remove});
            this.setState(
              produce((draft: Draft): void => {
                draft.remove.roleIds = '';
                draft.delectShowModel = false;
              }),
            );
          }}
          footer={null}
        >
          <div className="delete_titlep">
            <p className="titlep">确定要删除选中数据吗？</p>
          </div>
          <div className={sty.footBtnArea}>
            <div
              className={sty.foot_delete_btn}
              onClick={() => {
                this.handledelete();
              }}
            >
              确定
            </div>
            <div
              className={sty.foot_delete_btn}
              onClick={() => {
                this.setState(
                  produce((draft: Draft): void => {
                    draft.remove.roleIds = '';
                    draft.delectShowModel = false;
                  }),
                );
              }}
            >
              取消
            </div>
          </div>
        </Modal>
        <Modal
          visible={this.state.isShowModel}
          title="添加用户到角色"
          centered={true}
          // onOk={this.handleOk}
          className="roleuser_box"
          onCancel={() => {
            this.setState(
              produce((draft: Draft): void => {
                draft.parameters1.surLoginName = '';
                draft.parameters1.surPhoneNumber = '';
                draft.parameters1.pageNum = 1;
                draft.isShowModel = false;
                draft.tableData1 = [];
              }),
              () => {
                this.handleLoading();
              },
            );
          }}
          footer={null}
        >
          <div style={{ clear: 'both' }}>
            <div className={styles['dev-search']}>
              <div className={styles['dev-search-select']}>
                <Input
                  addonBefore="登录名称"
                  type="text"
                  value={this.state.parameters1.surLoginName}
                  onChange={e => {
                    let val = e.target.value;
                    this.setState(
                      produce((draft: Draft): void => {
                        draft.parameters1.surLoginName = val;
                        // draft.roleId = e.target.value;
                      }),
                      () => {},
                    );
                  }}
                />
              </div>
              <div className={styles['dev-search-select']}>
                <Input
                  addonBefore="电话号码"
                  type="text"
                  value={this.state.parameters1.surPhoneNumber}
                  onChange={e => {
                    const reg = /^-?(0|[1-9][0-9]*)(\.[0-9]*)?$/;
                    let datachange = e.target.value.replace(/[, ]/g, '');
                    if (
                      (!isNaN(datachange) && reg.test(datachange)) ||
                      datachange === '' ||
                      datachange === '-'
                    ) {
                      this.setState(
                        produce((draft: Draft): void => {
                          draft.parameters1.surPhoneNumber = datachange;
                          // draft.value = datachange;
                        }),
                      );
                    } else {
                      this.setState(
                        produce((draft: Draft): void => {
                          draft.parameters1.surPhoneNumber = '';
                          // draft.value = '';
                        }),
                        () => {
                          message.error('请填写数字');
                        },
                      );
                    }
                  }}
                />
              </div>

              <Button
                className={styles.search}
                size="large"
                onClick={() => {
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.parameters1.pageNum = 1;
                      draft.parameters1.pageSize = 5;
                      draft.pageNum1 = 1;
                    }),
                    () => {
                      this.handleUnaAllocatedRoleUser();
                    },
                  );
                }}
              >
                搜索
              </Button>
              <Button
                className={styles.search}
                size="large"
                onClick={() => {
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.parameters1.surPhoneNumber = '';
                      draft.parameters1.surLoginName = '';
                    }),
                    () => {},
                  );
                }}
              >
                重置
              </Button>
            </div>
          </div>
          <div className={'tableArea1'}>
            <Table dataSource={this.state.tableData1} pagination={false} rowKey="surUserId">
              <Column title="登陆名称" align="center" dataIndex="surLoginName" key="surLoginName" />
              <Column title="用户名称" align="center" dataIndex="surUserName" key="surUserName" />
              <Column title="邮箱" align="center" dataIndex="surEmail" key="surEmail" />
              <Column
                title="手机号码"
                align="center"
                dataIndex="surPhoneNumber"
                key="surPhoneNumber"
              />
              <Column
                title="用户状态"
                align="center"
                dataIndex="surStatus"
                key="surStatus"
                render={(_text: number, _record: any) => {
                  return _record.surStatus == 0 ? (
                    <span style={{ color: 'rgb(69, 235, 167)' }}>正常</span>
                  ) : (
                    <span style={{ color: '#cb3203' }}>停用</span>
                  );
                }}
              />
              <Column
                title="创建时间"
                align="center"
                dataIndex="surCreateTime"
                key="surCreateTime"
              />
              <Column
                title="操作"
                align="center"
                key="action"
                render={(_text: number, _record: any) => (
                  <span>
                    {/* {isMenuVisible('system:roleUser:insertUserRole') && ( */}
                      <a
                        onClick={() => {
                          this.insertUserRole(_record);
                        }}
                        style={{ color: 'rgb(69, 235, 167)' }}
                      >
                        添加
                      </a>
                    {/* )} */}
                  </span>
                )}
              />
            </Table>
          </div>
          <div className={sty.pageArea}>
            <Pagination
              className={styles.pageHandle}
              showQuickJumper={false}
              defaultCurrent={1}
              pageSize={5}
              current={this.state.pageNum1}
              total={this.state.pageTotal1}
              onChange={pageNo => {
                let datachange = pageNo;
                this.setState(
                  produce((draft: Draft): void => {
                    draft.parameters1.pageNum = datachange;
                    draft.pageNum1 = datachange;
                  }),
                  () => {
                    this.handleUnaAllocatedRoleUser();
                  },
                );
              }}
            />
            <span className="pagination-title-box">
              第{this.state.pageNum1}/{Math.ceil(this.state.pageTotal1 / this.state.pageSize1)}页 共
              {this.state.pageTotal1}条
            </span>
          </div>
          <div className={styles.btnArea}>
            <div style={{ textAlign: 'center', height: 50, width: 300, margin: '0 auto' }}>
              <div
                style={{ width: 180, height: 40, float: 'none' }}
                className={sty.foot_btn}
                onClick={() => {
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.parameters1.surLoginName = '';
                      draft.parameters1.surPhoneNumber = '';
                      draft.parameters1.pageNum = 1;
                      draft.isShowModel = false;
                      draft.tableData1 = [];
                    }),
                    () => {
                      this.handleLoading();
                    },
                  );
                }}
                type="primary"
              >
                确定
              </div>
              <div
                style={{ width: 180, height: 40, float: 'none' }}
                className={sty.foot_btn}
                onClick={() => {
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.parameters1.surLoginName = '';
                      draft.parameters1.surPhoneNumber = '';
                      draft.parameters1.pageNum = 1;
                      draft.isShowModel = false;
                      draft.tableData1 = [];
                    }),
                    () => {
                      this.handleLoading();
                    },
                  );
                }}
                type="primary"
              >
                取消
              </div>
            </div>
          </div>
        </Modal>
      </div>
    );
  }
}
export default connect(({ loading, systemDevice }: any) => ({
  loading: loading.effects['systemDevice/applyDeviceTreeData'],
  systemDevice: systemDevice.applyDeviceLists,
  treeData: systemDevice.applyDeviceTreeData,
}))(distributionUser);
